package com.atsmart.app.activity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.util.List;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.LoadingAdapter;
import com.atsmart.app.adapter.ReportSaveHistoryAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.http.HttpHelper;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.ContextInfo;
import com.atsmart.app.model.ReportHistoryInfo;
import com.atsmart.app.model.ResultInfo;
import com.atsmart.app.model.TemplateInfo;
import com.atsmart.app.model.TemplateListInfo;
import com.atsmart.app.model.UploadInfo;
import com.atsmart.app.model.UploadItemInfo;
import com.atsmart.app.sql.ContextSqlHelper;
import com.atsmart.app.sql.TempFromTaskSql;
import com.atsmart.app.sql.TemplateInfoSql;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.google.json.annotations.SerializedName;

public class ReportSaveHistoryActivity extends BaseActivity implements
		LoadingAdapter.Delegate, LoadingAdapter.OnLoadingRowShowingHandler,
		OnClickListener {

	private ListView listView;
	private Button refresh;
	private int historyType;
	private List<ContextInfo> histories;
	private ReportSaveHistoryAdapter adapter;
	private static final int pageSize = 20;
	private boolean isNeedLoading = false;
	private int totalRow;
	private int pageIndex = 0;
	private static boolean asyntaskIsFinished = true;
	private static final String TAG = ReportSaveHistoryActivity.class.getName();
	private ContextSqlHelper csql = null;
	private Button btnSearch;
	private long length = 0;
	private long re_length = 0;
	private String capre = null;
	private int vId;
	private int rId;
	private int count = 1;
	private int zongcount;
	private String uppath = "";
	private boolean vflag = false;
	private boolean iflag = false;
	private boolean rflag = false;
	private ProgressDialog pd = null;
	private Thread th = null;
	private static boolean flag = true;
	private TemplateInfoSql templateInfoSql = null;
	private TempFromTaskSql tesql = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reportsave_list_layout);
		listView = (ListView) findViewById(R.id.listview);
		refresh = (Button) findViewById(R.id.btn_refresh);
		btnSearch = (Button) findViewById(R.id.savebtn_search);
		btnSearch.setText("上传");
		refresh.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
		csql = new ContextSqlHelper();
		csql.open(BizApp.getInstance().getSqlHelper());
		flag = true;
		templateInfoSql = new TemplateInfoSql();
		templateInfoSql.open(BizApp.getInstance().getSqlHelper());
		tesql = new TempFromTaskSql();
		tesql.open(BizApp.getInstance().getSqlHelper());
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_refresh) {
			if (asyntaskIsFinished) {
				showLoading();
				pageIndex = 0;
				getData();
				asyntaskIsFinished = false;
			}
		}
		if (v.getId() == R.id.savebtn_search) {
			if ((BizApp.getInstance().isNetworkAvailable()
					|| BizApp.getInstance().isWiFiActive())&&BizApp.getInstance().keeping) {
				pd = new ProgressDialog(this);
				pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				pd.setMessage("正在上传");
				pd.setCancelable(true);
				pd.show();
				upload();
			} else {
				Toast.makeText(this, "无可用网络！", Toast.LENGTH_SHORT).show();
			}
		}
	}

	private String name = "";
	public void upload() {
		pd.show();
		if (th != null) {
			th.stop();
		}
		th = new Thread() {
			public void run() {
				try {
					flag = true;
					List<ContextInfo> li = csql.getContextInfo();
					if (li != null && li.size() > 0) {
						zongcount = li.size();
						for (ContextInfo ci : li) {
							if (!flag) {
								break;
							}
							uppath = ci.getContext();
							name = ci.getName();
							if (ci.getVediopath() != null
									&& !"".equals(ci.getVediopath())) {
								vflag = true;
								vedio(ci.getContext(), ci.getVediopath(),
										ci.getId());
							}
							if (ci.getRecpath() != null
									&& !"".equals(ci.getRecpath())) {
								rflag = true;
								record(ci.getRecpath());
							}
							if (ci.getImgpath() != null
									&& !"".equals(ci.getImgpath())) {
								iflag = true;
								im(ci.getContext(), ci.getImgpath(), ci.getId());
							}
							if (!vflag && !rflag && !iflag) {
								Log.e("TAG","ci: ="+ new Gson().toJson(ci));
								uploadContent(uppath, ci.getId(), ci.getName());
							}
							getData();
						}
					}
				} catch (Exception e) {
					if (pd != null) {
						pd.dismiss();
					}
				}
			}
		};
		th.start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (pd != null) {
			pd.cancel();
		}
		flag = false;
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (asyntaskIsFinished) {
			showLoading();
			pageIndex = 0;
			getData();
			asyntaskIsFinished = false;
		}
		flag = true;
	}

	private void getData() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<List<ContextInfo>>() {

			@Override
			protected List<ContextInfo> callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				return csql.getContextInfo();
			}

			@Override
			protected void runWithResult(List<ContextInfo> result)
					throws Exception {
				if (result != null && result.size() > 0) {
					histories = result;
					for (ContextInfo c : histories) {
						if (c.getType() == 0) {
							c.setName(c.getName() + "(汇报)");
						} else {
							c.setName(c.getName() + "(任务)");
						}

					}

					bindData();
				} else {
					isEmpty();
				}
				asyntaskIsFinished = true;
				hideLoading();
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(List<ContextInfo> result, int iErrorCode)
					throws Exception {
				loadingFailed(TAG, iErrorCode);
				asyntaskIsFinished = true;
				// TaskForAllActivity.hideLoading();
				hideLoading();
			}
		}.execute();
	}

	private void isEmpty() {
		if (histories == null || histories.size() == 0) {
			Toast.makeText(this, "本地汇报数据为空", Toast.LENGTH_SHORT).show();
		}
	}

	private void bindData() {
		if (adapter == null || pageIndex == 0) {
			adapter = new ReportSaveHistoryAdapter(histories);
			adapter.setDelegate(this);
			adapter.setHandler(this);
			listView.setAdapter(adapter);
		} else {
			if (pageIndex >= 1) {
				adapter.appendDataSource(histories);
				adapter.notifyDataSetChanged();
			}
		}
		if (totalRow > (pageIndex + 1) * pageSize) {
			isNeedLoading = true;
		} else {
			isNeedLoading = false;
		}
	}

	@Override
	public void onLoadingRowShowing(LoadingAdapter adapter) {
		if (pageIndex * pageSize < totalRow) {
			if (asyntaskIsFinished) {
				pageIndex++;
				getData();
				asyntaskIsFinished = false;
			}
		}

	}

	@Override
	public boolean needLoading() {
		return isNeedLoading;
	}


	private void uploadContent(final String uploadInfo, final int id, final String name) {
		ResultInfo in = null;
		try {
			in = ServiceHelper.getInstance().postData(ServiceHost.upload(),
					uploadInfo, ResultInfo.class);
		} catch (Exception e) {
			if(PrefsUtils.getURL().equals(StringUtil.URL1)){
				PrefsUtils.setURL(StringUtil.URL2);
			}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
				PrefsUtils.setURL(StringUtil.URL1);
			}
			try{
				in = ServiceHelper.getInstance().postData(ServiceHost.upload(),
						uploadInfo, ResultInfo.class);
			}catch (Exception ex) {
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
			}
		} 
		Message msg = handler.obtainMessage();
		msg.getData().putInt("step", (int) ((count / (float) zongcount) * 100));
		handler.sendMessage(msg);
		
		if(in != null && in.result == 0){
			UploadInfo info = new Gson().fromJson(uploadInfo, UploadInfo.class);
			String temname = "";
			if(info.type == 1){
				try{
					TemplateListInfo templateinfo = templateInfoSql.getTemplateInfo(0, templateInfoSql.getCount());
					for(TemplateInfo teminfo: templateinfo.getTemplates()){
						if(info.id == teminfo.getId()){
							temname = teminfo.getName();
						}
					}
					ReportHistoryInfo history = new ReportHistoryInfo();
					history.name = temname + "(汇报)";
					history.date = StringUtil.getReportTime();
					history.type = 1;
					BizApp.getInstance().getSqlHelper().addHistory(history);
				}catch (Exception e) {
				}
			}else if(info.type == 3){
				temname = name;
				ReportHistoryInfo history = new ReportHistoryInfo();
				history.name = temname + "(任务)";
				history.date = StringUtil.getReportTime();
				history.type = 3;
				BizApp.getInstance().getSqlHelper().addHistory(history);
			}
		}
		if (in != null) {
			csql.deleteAttribute(id);
		}
		if (count == zongcount) {
			finish();
		}
		Log.e("count", String.valueOf(count));
		count++;
	}

	final private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int nStep = msg.getData().getInt("step", -1);
			// Log.e(TAG, "step->" + nStep);
			if (nStep == -1) {
				pd.dismiss();
			} else {
				pd.setProgress(nStep);
			}
		}
	};

	private void vedio(final String up, final String path, int id) {
		String[] paths = path.split(",");
		vId = Integer.valueOf(paths[0]);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[8 * 1024];
		try {
			CommonBody body = new CommonBody();
			body.setCommand(3);
			body.setImsi(BizApp.getInstance().getIMSI());
			body.setVersion(getString(R.string.app_version));
			body.setFile("3gp");
			body.setBegin_index(0);
			String reqBody = new Gson().toJson(body);
			reqBody = reqBody + "\r\n\r\n";
			bos.write(reqBody.getBytes("ISO-8859-1"));
			FileInputStream fis = new FileInputStream(paths[1]);// "/mnt/sdcard/atsmart/example.jpg");//
			// Bitmap bitmap = BitmapFactory.decodeStream(fis);
			// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			for (int readNum; (readNum = fis.read(buf)) != -1;) {
				if (bos.toByteArray().length < 100000) {
					bos.write(buf, 0, readNum);
					length += buf.length;
				} else {
					break;
				}
			}
			bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
			fis.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		uploadVedio(bos.toByteArray(), paths[1], id);
		// List<byte[]> aa = readImageAsByteArray(3, capre, "3gp");
		// if (aa != null && aa.size() > 0) {
		// for (byte[] bb : aa) {
		// uploadVedio(bb);
		// }
		// }
	}

	private void uploadVedio(final byte[] bb, final String path, final int id) {

		new AsyncTask<Void, Void, ImgPathInfo>() {

			@Override
			protected ImgPathInfo doInBackground(Void... params) {
				try {
					return new Gson().fromJson(postOnService(bb),
							ImgPathInfo.class);
				} catch (Exception e) {
					e.printStackTrace();
				}  
				return null;
			}

			protected void onPostExecute(ImgPathInfo result) {
				dealWithResult(result, bb, path, id);
			};
		}.execute();
	}

	private void dealWithResult(ImgPathInfo result, byte[] bb, String path,
			int id) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[8 * 1024];
		try {
			CommonBody body = new CommonBody();
			body.setCommand(3);
			body.setImsi(BizApp.getInstance().getIMSI());
			body.setVersion(getString(R.string.app_version));
			if (result != null) {
				body.setFile(result.path);
				body.setBegin_index(length);
				String reqBody = new Gson().toJson(body);
				reqBody = reqBody + "\r\n\r\n";
				bos.write(reqBody.getBytes("ISO-8859-1"));
				FileInputStream fis = new FileInputStream(path);// "/mnt/sdcard/atsmart/example.jpg");//
				// Bitmap bitmap = BitmapFactory.decodeStream(fis);
				// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				int cc = 0;
				for (int readNum; (readNum = fis.read(buf)) != -1;) {
					cc += buf.length;
				}
				Log.e("length", String.valueOf(length));
				Log.e("cc", String.valueOf(cc));
				if (cc == length) {
					capre = null;
					UploadItemInfo itemInfo = new UploadItemInfo();
					itemInfo.id = vId;
					itemInfo.type = 8;
					if (result != null) {
						itemInfo.value = result.path;
					}
					String start = uppath.substring(0, uppath.indexOf("]"));
					start = start + "," + new Gson().toJson(itemInfo);
					String end = uppath.substring(uppath.indexOf("]"));
					Log.e("aaadddss", start + end);
					uppath = start + end;
					uploadContent(uppath, id, name);
				} else {
					fis = new FileInputStream(capre);
					long count = 0;
					for (int readNum; (readNum = fis.read(buf)) != -1;) {
						count += buf.length;
						if (count > length) {
							if (bos.toByteArray().length < 100000) {
								bos.write(buf, 0, readNum);
								length += buf.length;
							} else {
								break;
							}
						}

					}
					bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
					fis.close();
				}
			} else {
				uploadVedio(bb, path, id);
			}

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	private void record(String path) {
		String[] paths = path.split(",");
		rId = Integer.valueOf(paths[0]);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[8 * 1024];
		try {
			CommonBody body = new CommonBody();
			body.setCommand(2);
			body.setImsi(BizApp.getInstance().getIMSI());
			body.setVersion(getString(R.string.app_version));
			body.setFile("amr");
			body.setBegin_index(0);
			String reqBody = new Gson().toJson(body);
			reqBody = reqBody + "\r\n\r\n";
			bos.write(reqBody.getBytes("ISO-8859-1"));
			FileInputStream fis = new FileInputStream(paths[1]);// "/mnt/sdcard/atsmart/example.jpg");//
			// Bitmap bitmap = BitmapFactory.decodeStream(fis);
			// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			for (int readNum; (readNum = fis.read(buf)) != -1;) {
				if (bos.toByteArray().length < 100000) {
					bos.write(buf, 0, readNum);
					re_length += buf.length;
				} else {
					break;
				}
			}
			bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
			fis.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		uploadRecord(bos.toByteArray(), paths[1]);
	}

	private void uploadRecord(final byte[] bb, final String path) {

		new AsyncTask<Void, Void, ImgPathInfo>() {

			@Override
			protected ImgPathInfo doInBackground(Void... params) {
				try {
					return new Gson().fromJson(postOnService(bb),
							ImgPathInfo.class);
				} catch (Exception e) {
					e.printStackTrace();
				}  
				return null;
			}

			protected void onPostExecute(ImgPathInfo result) {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				byte[] buf = new byte[8 * 1024];
				try {
					CommonBody body = new CommonBody();
					body.setCommand(2);
					body.setImsi(BizApp.getInstance().getIMSI());
					body.setVersion(getString(R.string.app_version));
					body.setFile(result.path);
					body.setBegin_index(re_length);
					String reqBody = new Gson().toJson(body);
					reqBody = reqBody + "\r\n\r\n";
					bos.write(reqBody.getBytes("ISO-8859-1"));
					FileInputStream fis = new FileInputStream(path);// "/mnt/sdcard/atsmart/example.jpg");//
					// Bitmap bitmap = BitmapFactory.decodeStream(fis);
					// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
					int cc = 0;
					for (int readNum; (readNum = fis.read(buf)) != -1;) {
						cc += buf.length;
					}
					// Log.e("re_length", String.valueOf(re_length));
					// Log.e("cc", String.valueOf(cc));
					if (cc == re_length) {
						PrefsUtils.setReportRecordPath("");
						UploadItemInfo itemInfo = new UploadItemInfo();
						itemInfo.id = rId;
						itemInfo.type = 7;
						if (result != null) {
							itemInfo.value = result.path;
						}
						String start = uppath.substring(0, uppath.indexOf("]"));
						start = start + "," + new Gson().toJson(itemInfo);
						String end = uppath.substring(uppath.indexOf("]"));
						Log.e("aaadddss", start + end);
						uppath = start + end;
					} else {
						fis = new FileInputStream(
								PrefsUtils.getReportRecordPath());
						long count = 0;
						for (int readNum; (readNum = fis.read(buf)) != -1;) {
							count += buf.length;
							if (count > re_length) {
								if (bos.toByteArray().length < 100000) {
									bos.write(buf, 0, readNum);
									re_length += buf.length;
								} else {
									break;
								}
							}

						}
						bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
						fis.close();
						uploadRecord(bos.toByteArray(), path);
					}

				} catch (IOException ex) {
					ex.printStackTrace();
				}
				PrefsUtils.setReportRecordPath("");
			};
		}.execute();
	}

	private class ImgPathInfo implements Serializable {
		/**
		 *
		 */
		private static final long serialVersionUID = 7216739021733421705L;
		/**
		 *
		 */
		@SerializedName("file")
		public String path;
	}

	private void im(final String up, final String path, final int id) {
		String[] str = path.split(";");
		for (int i = 0; i < str.length; i++) {
			String[] str1 = str[i].split(",");
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buf = new byte[8 * 1024];
			try {
				CommonBody body = new CommonBody();
				body.setCommand(1);
				body.setImsi(BizApp.getInstance().getIMSI());
				body.setVersion(getString(R.string.app_version));
				body.setFile("jpg");
				body.setBegin_index(0);
				String reqBody = new Gson().toJson(body);
				reqBody = reqBody + "\r\n\r\n";
				bos.write(reqBody.getBytes("ISO-8859-1"));
				FileInputStream fis = new FileInputStream(str1[1]);// "/mnt/sdcard/atsmart/example.jpg");//
				// Bitmap bitmap = BitmapFactory.decodeStream(fis);
				// bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
				// bos);
				for (int readNum; (readNum = fis.read(buf)) != -1;) {
					if (bos.toByteArray().length < 100000) {
						bos.write(buf, 0, readNum);
						length += buf.length;
					} else {
						break;
					}
				}
				bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
				fis.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
			// Message msg = this.handler.obtainMessage();
			// msg.getData().putInt("step",
			// (int) ((i + 1 / (float) str.length) * 100));
			// this.handler.sendMessage(msg);
			if ((i + 1) == str.length) {
				uploadImage(Integer.valueOf(str1[0]), bos.toByteArray(), true,
						up, id);
			} else {
				uploadImage(Integer.valueOf(str1[0]), bos.toByteArray(), false,
						up, id);
			}

		}
	}

	 
	private void uploadImage(final int ss, final byte[] bb, final boolean flag,
			final String up, final int id) {
		ImgPathInfo result = null;
		try {
			result = new Gson().fromJson(postOnService(bb), ImgPathInfo.class);
		} catch (Exception e) {
			e.printStackTrace();
		}  
		UploadItemInfo itemInfo = new UploadItemInfo();
		itemInfo.id = ss;
		itemInfo.type = 4;
		if (result != null) {
			itemInfo.value = result.path;
			String start = up.substring(0, up.indexOf("]"));
			start = start + "," + new Gson().toJson(itemInfo);
			String end = up.substring(up.indexOf("]"));
			Log.e("aaadddss", start + end);
			uppath = start + end;
			if (!vflag) {
				uploadContent(uppath, id, name);
			}
		} else {
			itemInfo.value = "";
			if (count == zongcount) {
				finish();
			}
			count++;
		}
	}

	protected String postOnService(byte[] bb) throws MalformedURLException,
			IOException, BizException {
		HttpHelper http = new HttpHelper(bb.length);
		http.setCONNECTION_TIMEOUT(20000);
		http.setREAD_TIMEOUT(20000);
		try {
			http.createMode().url(ServiceHost.uploadImage())
					.header("Content-Type", "charset=ISO-8859-1")
					.header("Accept-Charset", "ISO-8859-1");
			// byte[] bb= reqBody.getBytes("ISO-8859-1");
			http.body(new ByteArrayInputStream(bb)).send();

		} catch (Exception ex) {
			if(PrefsUtils.getURL().equals(StringUtil.URL1)){
				PrefsUtils.setURL(StringUtil.URL2);
			}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
				PrefsUtils.setURL(StringUtil.URL1);
			}
			try{
				http.createMode().url(ServiceHost.uploadImage())
				.header("Content-Type", "charset=ISO-8859-1")
				.header("Accept-Charset", "ISO-8859-1");
				http.body(new ByteArrayInputStream(bb)).send();
			}catch (Exception e) {
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
			}
		}
		String bodyString = "";
		if (http.isSuccessful()) {
			bodyString = http.getBodyAsString();
			if (bodyString != null) {
				bodyString = bodyString.substring(
						bodyString.indexOf("\r\n\r\n"), bodyString.length());
				return bodyString;
			} else {
				return "";
			}
		} else {
			http.send();
			if (http.isSuccessful()) {
				bodyString = http.getBodyAsString();
				if (bodyString != null) {
					return bodyString;
				} else {
					return "";
				}
			}
			final int responseCode = http.getResponseCode();
			throw new BizException(responseCode);
		}
	}

}
